package com.tools.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import org.apache.commons.lang3.StringUtils;


/**
 * 阿里JSON工具类
 */
public class JSONUtils {

    /**
     * 只转换filterAttr中的属性
     *
     * @param o
     * @param filterAttr
     * @param isFilter 包含或不包含
     * @return
     */
    private static String getFiletrJsonString(Object o, String filterAttr, boolean isFilter) {
        FastJsonPropertyFilter filter = new FastJsonPropertyFilter(StringUtils.trimToEmpty(filterAttr), isFilter);
        return JSONObject.toJSONString(o, filter);
    }

    private static class FastJsonPropertyFilter implements PropertyFilter{
        /**
         * 默认构造器
         * @param str
         * @param isFilter
         */
        private boolean isFilter;
        private String[] attrArr;
        public FastJsonPropertyFilter(String str,boolean isFilter){
            this.attrArr = str.split(",");
            this.isFilter=isFilter;
        }

        @Override
        public boolean apply(Object object, String name, Object value) {
            if (name == null) {
                return true;
            }
            for(String s:attrArr){
                if(s.equals(name)){
                    return isFilter;
                }
            }
            return true;
        }
    }
}
